const { sqlite3 } = require('../../mysql')


// 获取漫画列表
const cardList = async (ctx) => {
    console.log('ctx.query:', ctx.query)
    let formData = ctx.query
    let offset = (formData.currentPage - 1) * formData.pageSize
    let limit = formData.pageSize
    let keyword = formData.title
    if (keyword) {
        data = await sqlite3('card')
            .where('title', 'LIKE', '%' + keyword + '%')
            .orderBy('id', 'desc')
            .select()
            .limit(formData.limit)
            .offset(offset)
        total = data.length
    } else {
        limitdata = await sqlite3('card').count({ total: '*' })
        data = await sqlite3('card').orderBy('id', 'Asc').select().limit(limit).offset(offset)
        total = limitdata[0].total
        console.log('pageSize:', formData.currentPage, 'currentPage:', limit)
    }
    if (data) {
        ctx.body = {
            success: true,
            data: {
                list: data,
                total,
                pageSize: Number(limit),
                currentPage: Number(formData.currentPage)
            },
        }
    } else {
        ctx.body = {
            success: false
        }
    }
}

// 添加
const cardCreate = async (ctx) => {
    console.log('ctx:', ctx.request.body)
    let formData = ctx.request.body
    const data = await sqlite3('card').insert(
        formData
    )
    console.log(data)
    if (data) {
        ctx.body = {
            success: 200,
            data: "success",
        }
    } else {
        ctx.body = {
            success: false
        }
    }
}

// 修改
const cardUpdate = async (ctx) => {
    console.log('ctx:', ctx.request.body)
    let formData = ctx.request.body
    const data = await sqlite3('card')
        .where('id', formData.id)
        .update(formData)
    // console.log(data)
    if (data) {
        ctx.body = {
            success: 200,
            data: "success"
        }
    } else {
        ctx.body = {
            success: false
        }
    }
}

// 删除
const cardDelete = async (ctx) => {
    console.log('ctx:', ctx.request.body)
    let formData = ctx.request.body
    const data = await sqlite3('card')
        .where('id', formData.id).del()
    console.log(data)
    if (data) {
        ctx.body = {
            code: 200,
            data: "success"
        }
    } else {
        ctx.body = {
            code: false
        }
    }
}

module.exports = { cardList, cardCreate, cardUpdate, cardDelete }
